<template>
  <div class="main">
    <!-- 搜索表单 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="操作用户">
          <el-input
            v-model="filterForm.username"
            placeholder="请输入用户名"
            clearable
            class="!w-[150px]"
          />
        </el-form-item>
        <el-form-item label="操作模块">
          <el-select
            v-model="filterForm.module"
            placeholder="请选择模块"
            clearable
            class="!w-[150px]"
          >
            <el-option label="用户管理" value="user" />
            <el-option label="角色管理" value="role" />
            <el-option label="活动管理" value="activity" />
            <el-option label="赛事管理" value="match" />
            <el-option label="比赛管理" value="competition" />
            <el-option label="俱乐部管理" value="club" />
            <el-option label="订单管理" value="order" />
            <el-option label="资讯管理" value="news" />
            <el-option label="广告管理" value="ad" />
            <el-option label="培训管理" value="training" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select
            v-model="filterForm.action"
            placeholder="请选择操作类型"
            clearable
            class="!w-[120px]"
          >
            <el-option label="新增" value="create" />
            <el-option label="编辑" value="update" />
            <el-option label="删除" value="delete" />
            <el-option label="查看" value="view" />
            <el-option label="导出" value="export" />
            <el-option label="登录" value="login" />
            <el-option label="登出" value="logout" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择状态"
            clearable
            class="!w-[120px]"
          >
            <el-option label="成功" value="success" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            class="!w-[350px]"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline :icon="Search" />
            查询
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline :icon="Refresh" />
            重置
          </el-button>
          <el-button type="success" @click="handleExport">
            <IconifyIconOffline :icon="Download" />
            导出
          </el-button>
          <el-button type="danger" @click="handleClear" :disabled="!selectedRows.length">
            <IconifyIconOffline :icon="Delete" />
            清空日志
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total-icon">
              <IconifyIconOffline :icon="DocumentCopy" />
            </div>
            <div class="stat-info">
              <div class="stat-title">总日志数</div>
              <div class="stat-value">{{ logStats.total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon today-icon">
              <IconifyIconOffline :icon="Calendar" />
            </div>
            <div class="stat-info">
              <div class="stat-title">今日操作</div>
              <div class="stat-value">{{ logStats.today }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon success-icon">
              <IconifyIconOffline :icon="Check" />
            </div>
            <div class="stat-info">
              <div class="stat-title">成功操作</div>
              <div class="stat-value">{{ logStats.success }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon failed-icon">
              <IconifyIconOffline :icon="Close" />
            </div>
            <div class="stat-info">
              <div class="stat-title">失败操作</div>
              <div class="stat-value">{{ logStats.failed }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作日志列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>操作日志列表</span>
          <div>
            <el-button type="info" @click="handleRefresh">
              <IconifyIconOffline :icon="Refresh" />
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="logList" 
        style="width: 100%" 
        stripe 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="日志ID" width="80" />
        <el-table-column prop="username" label="操作用户" width="120" />
        <el-table-column prop="realName" label="用户姓名" width="100" />
        <el-table-column prop="module" label="操作模块" width="120">
          <template #default="{ row }">
            <el-tag size="small" :type="getModuleTagType(row.module)">
              {{ getModuleText(row.module) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="action" label="操作类型" width="100">
          <template #default="{ row }">
            <el-tag size="small" :type="getActionTagType(row.action)">
              {{ getActionText(row.action) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="操作描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="操作状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'success' ? 'success' : 'danger'" size="small">
              {{ row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" width="130" />
        <el-table-column prop="userAgent" label="用户代理" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tooltip :content="row.userAgent" placement="top">
              <span>{{ getBrowserInfo(row.userAgent) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="耗时(ms)" width="100" align="center">
          <template #default="{ row }">
            <span :class="getDurationClass(row.duration)">{{ row.duration }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="操作时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              <IconifyIconOffline :icon="View" />
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日志详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="操作日志详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
          <el-descriptions-item label="操作用户">{{ currentLog.username }}</el-descriptions-item>
          <el-descriptions-item label="用户姓名">{{ currentLog.realName }}</el-descriptions-item>
          <el-descriptions-item label="操作模块">
            <el-tag size="small" :type="getModuleTagType(currentLog.module)">
              {{ getModuleText(currentLog.module) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作类型">
            <el-tag size="small" :type="getActionTagType(currentLog.action)">
              {{ getActionText(currentLog.action) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作状态">
            <el-tag :type="currentLog.status === 'success' ? 'success' : 'danger'" size="small">
              {{ currentLog.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
          <el-descriptions-item label="操作耗时">{{ currentLog.duration }}ms</el-descriptions-item>
          <el-descriptions-item label="操作时间" :span="2">{{ formatDateTime(currentLog.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="操作描述" :span="2">{{ currentLog.description }}</el-descriptions-item>
        </el-descriptions>

        <!-- 请求参数 -->
        <div class="mt-4">
          <h4>请求参数</h4>
          <el-input
            v-model="currentLog.requestParams"
            type="textarea"
            :rows="6"
            readonly
            placeholder="无请求参数"
          />
        </div>

        <!-- 响应结果 -->
        <div class="mt-4">
          <h4>响应结果</h4>
          <el-input
            v-model="currentLog.responseData"
            type="textarea"
            :rows="6"
            readonly
            placeholder="无响应数据"
          />
        </div>

        <!-- 错误信息 -->
        <div v-if="currentLog.status === 'failed'" class="mt-4">
          <h4>错误信息</h4>
          <el-alert
            :title="currentLog.errorMessage"
            type="error"
            :closable="false"
            show-icon
          />
        </div>

        <!-- 用户代理信息 -->
        <div class="mt-4">
          <h4>用户代理信息</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="User-Agent">{{ currentLog.userAgent }}</el-descriptions-item>
            <el-descriptions-item label="浏览器信息">{{ getBrowserInfo(currentLog.userAgent) }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import DocumentCopy from "@iconify-icons/ep/document-copy";
import Calendar from "@iconify-icons/ep/calendar";
import Check from "@iconify-icons/ep/check";
import Close from "@iconify-icons/ep/close";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import Download from "@iconify-icons/ep/download";
import Delete from "@iconify-icons/ep/delete";
import View from "@iconify-icons/ep/view";
import dayjs from "dayjs";

defineOptions({
  name: "LogOperation"
});

// 筛选表单
const filterForm = ref({
  username: "",
  module: "",
  action: "",
  status: "",
  dateRange: []
});

// 日志统计
const logStats = ref({
  total: 15678,
  today: 234,
  success: 14892,
  failed: 786
});

// 日志列表
const logList = ref([]);
const loading = ref(false);
const selectedRows = ref([]);

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 弹窗控制
const detailDialogVisible = ref(false);

// 当前日志
const currentLog = ref(null);

// 获取模块标签类型
const getModuleTagType = (module: string) => {
  const moduleMap = {
    user: "primary",
    role: "success",
    activity: "warning",
    match: "info",
    competition: "danger",
    club: "primary",
    order: "warning",
    news: "success",
    ad: "info",
    training: "danger"
  };
  return moduleMap[module] || "info";
};

// 获取模块文本
const getModuleText = (module: string) => {
  const moduleMap = {
    user: "用户管理",
    role: "角色管理",
    activity: "活动管理",
    match: "赛事管理",
    competition: "比赛管理",
    club: "俱乐部管理",
    order: "订单管理",
    news: "资讯管理",
    ad: "广告管理",
    training: "培训管理"
  };
  return moduleMap[module] || module;
};

// 获取操作类型标签类型
const getActionTagType = (action: string) => {
  const actionMap = {
    create: "success",
    update: "warning",
    delete: "danger",
    view: "info",
    export: "primary",
    login: "success",
    logout: "info"
  };
  return actionMap[action] || "info";
};

// 获取操作类型文本
const getActionText = (action: string) => {
  const actionMap = {
    create: "新增",
    update: "编辑",
    delete: "删除",
    view: "查看",
    export: "导出",
    login: "登录",
    logout: "登出"
  };
  return actionMap[action] || action;
};

// 获取耗时样式类
const getDurationClass = (duration: number) => {
  if (duration < 100) return "text-green-600";
  if (duration < 500) return "text-orange-600";
  return "text-red-600";
};

// 获取浏览器信息
const getBrowserInfo = (userAgent: string) => {
  if (!userAgent) return "未知";
  
  if (userAgent.includes("Chrome")) return "Chrome";
  if (userAgent.includes("Firefox")) return "Firefox";
  if (userAgent.includes("Safari")) return "Safari";
  if (userAgent.includes("Edge")) return "Edge";
  if (userAgent.includes("Opera")) return "Opera";
  
  return "其他";
};

// 格式化日期时间
const formatDateTime = (date: string) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
};

// 生成模拟数据
const generateMockData = () => {
  const mockData = [];
  const usernames = ["admin", "operator1", "operator2", "manager1", "manager2"];
  const realNames = ["管理员", "操作员1", "操作员2", "经理1", "经理2"];
  const modules = ["user", "role", "activity", "match", "competition", "club", "order", "news", "ad", "training"];
  const actions = ["create", "update", "delete", "view", "export", "login", "logout"];
  const statuses = ["success", "failed"];
  const ips = ["192.168.1.100", "192.168.1.101", "192.168.1.102", "10.0.0.1", "172.16.0.1"];
  const userAgents = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15"
  ];
  
  for (let i = 1; i <= 100; i++) {
    const username = usernames[Math.floor(Math.random() * usernames.length)];
    const realName = realNames[usernames.indexOf(username)];
    const module = modules[Math.floor(Math.random() * modules.length)];
    const action = actions[Math.floor(Math.random() * actions.length)];
    const status = Math.random() > 0.1 ? "success" : "failed";
    const duration = Math.floor(Math.random() * 1000) + 10;
    const createTime = dayjs().subtract(Math.floor(Math.random() * 30), 'day')
      .subtract(Math.floor(Math.random() * 24), 'hour')
      .subtract(Math.floor(Math.random() * 60), 'minute');
    
    mockData.push({
      id: i,
      username,
      realName,
      module,
      action,
      description: `${getActionText(action)}${getModuleText(module)}数据`,
      status,
      ip: ips[Math.floor(Math.random() * ips.length)],
      userAgent: userAgents[Math.floor(Math.random() * userAgents.length)],
      duration,
      createTime: createTime.format('YYYY-MM-DD HH:mm:ss'),
      requestParams: JSON.stringify({
        id: i,
        name: `测试数据${i}`,
        type: "test"
      }, null, 2),
      responseData: status === "success" ? JSON.stringify({
        code: 200,
        message: "操作成功",
        data: { id: i }
      }, null, 2) : JSON.stringify({
        code: 500,
        message: "操作失败",
        error: "系统错误"
      }, null, 2),
      errorMessage: status === "failed" ? "系统内部错误，请联系管理员" : null
    });
  }
  
  return mockData.sort((a, b) => dayjs(b.createTime).valueOf() - dayjs(a.createTime).valueOf());
};

// 搜索
const handleSearch = () => {
  loadLogList();
};

// 重置
const handleReset = () => {
  filterForm.value = {
    username: "",
    module: "",
    action: "",
    status: "",
    dateRange: []
  };
  loadLogList();
};

// 导出
const handleExport = () => {
  ElMessage.success("导出功能开发中...");
};

// 清空日志
const handleClear = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要清空所有操作日志吗？此操作不可恢复！",
      "清空日志",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    
    ElMessage.success("日志清空成功");
    loadLogList();
  } catch (error) {
    // 用户取消
  }
};

// 刷新
const handleRefresh = () => {
  loadLogList();
};

// 查看详情
const handleView = (row: any) => {
  currentLog.value = row;
  detailDialogVisible.value = true;
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadLogList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadLogList();
};

// 加载日志列表
const loadLogList = async () => {
  try {
    loading.value = true;
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const mockData = generateMockData();
    logList.value = mockData.slice(
      (pagination.currentPage - 1) * pagination.pageSize,
      pagination.currentPage * pagination.pageSize
    );
    pagination.total = mockData.length;
  } catch (error) {
    ElMessage.error("加载日志列表失败");
  } finally {
    loading.value = false;
  }
};

// 组件挂载
onMounted(() => {
  loadLogList();
});
</script>

<style lang="scss" scoped>
.main {
  padding: 20px;
}

.filter-card {
  margin-bottom: 16px;
}

.stat-card {
  margin-bottom: 16px;
  
  .stat-content {
    display: flex;
    align-items: center;
    
    .stat-icon {
      width: 50px;
      height: 50px;
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      font-size: 20px;
      color: white;
      
      &.total-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }
      
      &.today-icon {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }
      
      &.success-icon {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }
      
      &.failed-icon {
        background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
      }
    }
    
    .stat-info {
      flex: 1;
      
      .stat-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;
      }
      
      .stat-value {
        font-size: 20px;
        font-weight: bold;
        color: #303133;
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.log-detail {
  h4 {
    margin: 20px 0 10px 0;
    color: #303133;
    font-weight: bold;
  }
}

@media (max-width: 768px) {
  .main {
    padding: 10px;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
    
    .stat-icon {
      margin-right: 0;
      margin-bottom: 12px;
    }
  }
  
  .pagination-container {
    text-align: center;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
}
</style>